/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swing.formularios;

import hibernate.dao.impl.ClienteDAOImpl;
import hibernate.dao.impl.TrabajadorDAOImpl;
import hibernate.entidades.Cliente;
import hibernate.entidades.DetallePedCli;
import hibernate.entidades.DetallePedCliPK;
import hibernate.entidades.PedidoCliente;
import hibernate.entidades.Productos;
import hibernate.entidades.Trabajadores;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import org.hibernate.exception.ConstraintViolationException;
import swing.modelos.ComboBoxModelo;
import swing.modelos.ModeloDetallesPedidoCliente;
import swing.modelos.ModeloPedidosClientes;
import swing.modelos.ModeloProductos;

/**
 *
 * @author ariel
 */
public class FormVenta extends javax.swing.JDialog {

    /**
     * El modelo de pedido cliente que viene de fuera.
     */
    private final ModeloPedidosClientes modeloPedCli;
    /**
     * El modelo de la tabla de la izquierda.
     */
    private ModeloProductos modeloProductos = new ModeloProductos();
    /**
     * El modelo de la tabla de la derecha.
     */
    private ModeloDetallesPedidoCliente modeloDetalles = new ModeloDetallesPedidoCliente();
    /**
     * cada detalle de pedido es una venta
     */
    private DetallePedCli venta;
    /**
     * el contador de líneas de venta
     */
    private short linea = 1;
    /**
     * El pedido para meterle los valores.
     */
    PedidoCliente pedido;

    /**
     * Creates new form FormVenta
     */
    public FormVenta(ModeloPedidosClientes modeloPedCli, java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.modeloPedCli = modeloPedCli;
        pedido = new PedidoCliente();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelForm = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        botonOk = new javax.swing.JButton();
        botonBorrar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        comboCliente = new javax.swing.JComboBox();
        comboEmpleado = new javax.swing.JComboBox();
        etiquetaEmpleado = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel9 = new javax.swing.JLabel();
        campoFecha = new com.toedter.calendar.JDateChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaDetalles = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaProductos = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        etiquetaSubTotal = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        etiquetaTotalIva = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        etiquetaDescuento = new javax.swing.JTextField();
        checkBoxDescuento = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Trajan Pro", 0, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(153, 51, 0));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("swing/formularios/Bundle"); // NOI18N
        jLabel1.setText(bundle.getString("FormVenta.jLabel1.text")); // NOI18N

        botonOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        botonOk.setText(bundle.getString("FormVenta.botonOk.text")); // NOI18N
        botonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonOkActionPerformed(evt);
            }
        });

        botonBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/gnome_edit_delete.png"))); // NOI18N
        botonBorrar.setText(bundle.getString("FormVenta.botonBorrar.text")); // NOI18N

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancel.png"))); // NOI18N
        botonCancelar.setText(bundle.getString("FormVenta.botonCancelar.text")); // NOI18N
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("FormVenta.jPanel1.border.title"))); // NOI18N

        jLabel5.setText(bundle.getString("FormVenta.jLabel5.text")); // NOI18N

        jLabel6.setText(bundle.getString("FormVenta.jLabel6.text")); // NOI18N

        comboCliente.setModel(new ComboBoxModelo(new ClienteDAOImpl()));
        comboCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboClienteActionPerformed(evt);
            }
        });

        comboEmpleado.setModel(new ComboBoxModelo(new TrabajadorDAOImpl()));

        etiquetaEmpleado.setText(bundle.getString("FormVenta.etiquetaEmpleado.text")); // NOI18N

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contado", "Crédito" }));

        jLabel8.setText(bundle.getString("FormVenta.jLabel8.text")); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        jLabel9.setText(bundle.getString("FormVenta.jLabel9.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(comboEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(etiquetaEmpleado)
                    .addComponent(campoFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(42, 42, 42)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane3)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etiquetaEmpleado)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(comboEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)))
        );

        tablaDetalles.setModel(modeloDetalles);
        jScrollPane1.setViewportView(tablaDetalles);

        tablaProductos.setModel(modeloProductos);
        jScrollPane2.setViewportView(tablaProductos);

        jLabel2.setText(bundle.getString("FormVenta.jLabel2.text")); // NOI18N

        jPanel2.setBackground(new java.awt.Color(102, 255, 0));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText(bundle.getString("FormVenta.jLabel3.text")); // NOI18N

        etiquetaSubTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        etiquetaSubTotal.setEnabled(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText(bundle.getString("FormVenta.jLabel4.text")); // NOI18N

        etiquetaTotalIva.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        etiquetaTotalIva.setEnabled(false);

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText(bundle.getString("FormVenta.jLabel7.text")); // NOI18N

        etiquetaDescuento.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        etiquetaDescuento.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(etiquetaSubTotal)
                        .addComponent(etiquetaDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(etiquetaTotalIva, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(etiquetaSubTotal, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(etiquetaDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(etiquetaTotalIva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        checkBoxDescuento.setSelected(true);
        checkBoxDescuento.setText(bundle.getString("FormVenta.checkBoxDescuento.text")); // NOI18N
        checkBoxDescuento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxDescuentoActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/right.png"))); // NOI18N
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setIconTextGap(5);
        jButton1.setMargin(new java.awt.Insets(5, 14, 2, 14));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/left.png"))); // NOI18N
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setIconTextGap(5);
        jButton2.setMargin(new java.awt.Insets(5, 14, 2, 14));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelFormLayout = new javax.swing.GroupLayout(panelForm);
        panelForm.setLayout(panelFormLayout);
        panelFormLayout.setHorizontalGroup(
            panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelFormLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelFormLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(panelFormLayout.createSequentialGroup()
                        .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelFormLayout.createSequentialGroup()
                                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(panelFormLayout.createSequentialGroup()
                                        .addComponent(botonOk)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(botonBorrar)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(botonCancelar))
                                    .addGroup(panelFormLayout.createSequentialGroup()
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, Short.MAX_VALUE)
                                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(panelFormLayout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(checkBoxDescuento)))
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        panelFormLayout.setVerticalGroup(
            panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelFormLayout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelFormLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelFormLayout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(checkBoxDescuento)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(panelFormLayout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(panelFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonOk)
                    .addComponent(botonBorrar)
                    .addComponent(botonCancelar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelForm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelForm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-888)/2, (screenSize.height-716)/2, 888, 716);
    }// </editor-fold>//GEN-END:initComponents

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_botonCancelarActionPerformed

    /**
     * El boton de OK debe de crear un pedido, añadirle los datos del pedido y
     * obtener la clave primaria autonumerica para pasarsela a la linea de
     * pedido que es una clave compuesta.
     *
     * @param evt
     */
    private void botonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonOkActionPerformed

        // TODO add your handling code here:
        try {
            pedido.setCodTrab((Trabajadores) comboEmpleado.getSelectedItem());
            pedido.setFecha(campoFecha.getDate());
            pedido.setDni((Cliente) comboCliente.getSelectedItem());
            pedido.setFPago(jComboBox1.getSelectedItem().toString());
            pedido.setObservaciones(jTextArea1.getText());
            pedido.setDescuento(((Cliente) comboCliente.getSelectedItem()).getDescuento());
            pedido.setTotal(Double.parseDouble(etiquetaTotalIva.getText()));
            //Añade la fila sin detalles
            modeloPedCli.addRow(pedido);
            //a los detalles les añade la clave de pedido
            modeloDetalles.setClavePedido(pedido.getCodPedCli());
            //Añade los detalles al pedido
            pedido.setDetallePedCliList(modeloDetalles.getDetalles());
            //Actualiza la fila
            modeloPedCli.addRow(pedido);
            //actualiza la tabla
            modeloProductos.aplicarStocks();
            modeloPedCli.fireTableDataChanged();
            this.dispose();
        } catch (ConstraintViolationException ex) {
            JOptionPane.showMessageDialog(this, "Rellene todos los campos", "Error", JOptionPane.OK_OPTION);
        }
    }//GEN-LAST:event_botonOkActionPerformed

    private void comboClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboClienteActionPerformed
        // TODO add your handling code here:
        actualizarTotales();
    }//GEN-LAST:event_comboClienteActionPerformed

    private void checkBoxDescuentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxDescuentoActionPerformed
        // TODO add your handling code here:
        actualizarTotales();
    }//GEN-LAST:event_checkBoxDescuentoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        try {
            Productos producto_detalle = modeloDetalles.getRow(tablaDetalles.getSelectedRow()).getCodStock();
            Productos producto = modeloProductos.getRow(producto_detalle.getCodStock());
            short stock = (short) (producto.getStock() + modeloDetalles.getRow(tablaDetalles.getSelectedRow()).getCantidad());
            producto.setStock(stock);
            // TODO add your handling code here:
            //removemos el producto del detalle
            modeloDetalles.removeDetalle(this.tablaDetalles.getSelectedRow());
            //reordenamos la numeración de líneas
            linea = modeloDetalles.reordenarLineas();

//            //Rellenamos la tabla nuevamente para actualizar los stocks originales
//            modeloProductos.rellenaTabla();
//            //Actualizamos el total de la factura
            modeloProductos.fireTableDataChanged();

            actualizarTotales();
        } catch (Exception ex) {
            Logger.getLogger(FormVenta.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            /**
             * Spinner Actual : 1 Mínimo : 1 Máximo : 30 Paso : 1
             */
            SpinnerNumberModel sModel = new SpinnerNumberModel(1, 1, 30, 1);
            JSpinner spinner = new JSpinner(sModel);
            Productos producto = this.modeloProductos.getRow(this.tablaProductos.getSelectedRow());
            /**
             * Show Message
             */
            JOptionPane.showMessageDialog(this, spinner);
            /**
             * creamos una venta para almacenar el detalle de linea
             */
            Short cantidad = Short.parseShort(spinner.getValue().toString());

            if (producto.getStock() >= cantidad) {
                venta = new DetallePedCli();
                venta.setCodStock(producto);
                venta.setDetallePedCliPK(new DetallePedCliPK(0, linea));
                venta.setCantidad(cantidad);
                venta.setPrecio(producto.getPrecio());
                modeloDetalles.addDetalle(venta);
                //removemos el stock del modeloProductos, pero no enviamos el cambio a la BD
                producto.setStock((short) (producto.getStock() - cantidad));
                modeloProductos.fireTableDataChanged();
                //modeloProductos.addRow(producto);
                linea++;
                actualizarTotales();
            } else {
                JOptionPane.showMessageDialog(this, "La cantidad supera el Stock disponible", "Error", JOptionPane.OK_OPTION);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            //Mensaje de error
            JOptionPane.showMessageDialog(this, "Seleccione un producto", "Error", JOptionPane.OK_OPTION);
        }        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBorrar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonOk;
    private com.toedter.calendar.JDateChooser campoFecha;
    private javax.swing.JCheckBox checkBoxDescuento;
    private javax.swing.JComboBox comboCliente;
    private javax.swing.JComboBox comboEmpleado;
    private javax.swing.JTextField etiquetaDescuento;
    private javax.swing.JLabel etiquetaEmpleado;
    private javax.swing.JTextField etiquetaSubTotal;
    private javax.swing.JTextField etiquetaTotalIva;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JPanel panelForm;
    private javax.swing.JTable tablaDetalles;
    private javax.swing.JTable tablaProductos;
    // End of variables declaration//GEN-END:variables

    private void actualizarTotales() {
        try {
            double descuento;
            double total;
            double subtotal = red(this.modeloDetalles.getTotal());

            this.etiquetaSubTotal.setText(String.valueOf(subtotal));
            if (comboCliente.getSelectedItem() != 0 && checkBoxDescuento.isSelected()) {
                Cliente cliente = (Cliente) comboCliente.getSelectedItem();
                descuento = (double) cliente.getDescuento() / 100;
            } else {
                descuento = 0;
            }
            this.etiquetaDescuento.setText(String.valueOf(red(subtotal * descuento)));
            total = red((subtotal - subtotal * descuento) * 1.21);
            this.etiquetaTotalIva.setText(String.valueOf(total));

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    public double red(double numero) {

        return Math.rint(numero * 100) / 100;

    }
}
